#include "raw_printf.h"
#include "stm32f4xx_usart.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
void USART_Config(void)
{
		GPIO_InitTypeDef GPIO_InitStruct;
		USART_InitTypeDef USART_InitStructure;
		
		RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
		
		GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF;
		GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
		GPIO_InitStruct.GPIO_OType=GPIO_OType_PP;
		GPIO_InitStruct.GPIO_PuPd=GPIO_PuPd_UP;

		GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10;
		GPIO_Init(GPIOA,&GPIO_InitStruct);

		GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
		GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
		
		USART_InitStructure.USART_BaudRate            = 115200;
		USART_InitStructure.USART_WordLength          = USART_WordLength_8b;
		USART_InitStructure.USART_StopBits            = USART_StopBits_1;
		USART_InitStructure.USART_Parity              = USART_Parity_No ;
		USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
		USART_InitStructure.USART_Mode                = USART_Mode_Rx | USART_Mode_Tx;

		USART_Init(USART1, &USART_InitStructure);
		USART_Cmd(USART1, ENABLE);	
    
}



int fputc(int ch,FILE *f)
{
		USART_SendData(USART1,(u8)ch);	                  
		while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)	
		{
		}											  
		return ch;		
}

int GetKey (void)
{ 
		while (!(USART1->SR & USART_FLAG_RXNE));	
		return ((int)(USART1->DR & 0x1FF));

}

void uart1_send_byte(unsigned char temp)
{
		USART_SendData(USART1, temp);
		while(USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET);
}

void raw_printk(const char *p_fmt, ...)
{
		unsigned int printed_len;
		char *s_p;
		va_list ap;
		char string_buff[128];
		s_p = string_buff;
		va_start(ap,p_fmt);
		printed_len = vsprintf(string_buff, p_fmt, ap);
		while(printed_len != 0) 
		{
				uart1_send_byte(*s_p++);
				printed_len--;
		}
}

